<template>
  <div class="cartConfirm fixed-top">
    <!-- 引入公共头部 -->
    <NavBar title="确认订单" url="/cart" back fixed/>
    <div class="order-box">
        <div class="van-address-list" style="padding-bottom: 0px">
          <div class="van-radio-group">
            <div class="address van-cell-group van-hairline--top-bottom">
              <div class="van-cell van-cell--clickable van-address-item">
                <div class="van-cell__value van-cell__value--alone">
                  <div class="van-radio">
                    <span class="van-radio__input">
                      <input type="radio" value="1" checked="checked" class="van-radio__control">
                      <i class="van-icon van-icon-checked"></i>
                    </span>
                    <span class="van-radio__label" @click="toAddress">
                      <div class="van-address-item__name">
                        {{confirmAddress.name}}&nbsp;&nbsp;&nbsp;&nbsp;{{confirmAddress.tel}}
                      </div>
                      <div class="van-address-item__address">
                        {{confirmAddress.province}}&nbsp;&nbsp;{{confirmAddress.city}}&nbsp;&nbsp;
                        {{confirmAddress.county}}&nbsp;&nbsp;{{confirmAddress.addressDetail}}
                      </div>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
    <ul class="order-ul" id="rightUl">
      <li v-for="item in list" :key="item.id">
        <tr>
          <td width="10%">
            <van-card
              tag="热卖"
              :num="item.num"
              :price="parseFloat(((item.isDiscount === 1 ? (item.discountPrice == null ? 0 : item.discountPrice) : item.salePrice) * memberDiscountPoint).toFixed(2))"
              :desc="'规格：'+item.property"
              :title="'商品名称：'+item.gdsName"
              :thumb="GLOBAL.baseImagePath + item.gdsUrl"
              :origin-price="item.isDiscount === 1 ? item.salePrice : undefined"
              style="background: #fff;"
            >
            </van-card>
          </td>
        </tr>
      </li>
    </ul>
    <van-submit-bar
      :loading="isLoading"
      :price="totalPrice*100"
      button-text="提交订单"
      @submit="onSubmit"
    >
    </van-submit-bar>
  </div>
</template>
<script>
import NavBar from '../../components/common/NavBar.vue'
import userApi from '../../api/user'
import orderApi from '../../api/order'
import { Dialog, Toast } from 'vant'
export default {
  name: 'cartConfirm',
  data () {
    return {
      memberDiscountPoint: 1,
      list: [],
      isLoading: false,
      confirmAddress: {id: 0, name: '', tel: '', province: '', city: '', county: '', addressDetail: ''}
    }
  },
  components: {
    NavBar
  },
  mounted () {
    this.getMemberDiscountPoint()
    this.getCarGodsList()
    this.getConfirmAddress()
  },
  computed: {
    totalPrice: function () {
      let num = 0
      if (this.list === null) {
        return 0
      }
      for (let i = 0; i < this.list.length; i++) {
        // 是否优惠
        if (this.list[i].isDiscount === 1) {
          num = this.list[i].num * this.list[i].discountPrice * this.memberDiscountPoint + num
        } else {
          num = this.list[i].num * this.list[i].salePrice * this.memberDiscountPoint + num
        }
      }
      return num
    },
    orderPrice: function () {
      let num = 0
      if (this.list === null) {
        return 0
      }
      for (let i = 0; i < this.list.length; i++) {
        num = this.list[i].num * this.list[i].salePrice + num
      }
      return num
    }
  },
  methods: {
    // 获取会员对应的折扣
    getMemberDiscountPoint () {
      let _this = this
      orderApi.getMemberDiscountPoint().then(function (res) {
        if (res.data.status === 0) {
          _this.memberDiscountPoint = res.data.re
        }
      })
    },
    // 点击提交按钮后禁用
    // 获取订单地址
    getConfirmAddress: function () {
      const _this = this
      // 获取num的值，0：获取用户默认地址，1：获取用户指定地址
      if (!this.$route.query.addressNum) {
        userApi.getDefaultAddress().then(function (res) {
          if (res.data.success) {
            if (res.data.re === null) {
              Dialog.confirm({
                title: '请先设置默认收货地址',
                message: '您还没有设置收货地址，请点击这里进行设置！'
              }).then(() => {
                _this.$router.push({path: '/user/addressAdd', query: {confirmNum: 2}})
              }).catch(() => {
                _this.$router.go(-1)
              })
            } else {
              _this.confirmAddress.id = res.data.re.id
              _this.confirmAddress.name = res.data.re.receiver
              _this.confirmAddress.tel = res.data.re.telephone
              _this.confirmAddress.province = res.data.re.province
              _this.confirmAddress.city = res.data.re.city
              _this.confirmAddress.county = res.data.re.district
              _this.confirmAddress.addressDetail = res.data.re.addrDetail
            }
          } else {
            Toast.fail('获取默认地址异常')
          }
        }).catch(function () {
          Toast.fail('获取默认地址异常')
        })
      } else if (this.$route.query.confirmAddressId) {
        userApi.getAddress(this.$route.query.confirmAddressId).then(function (res) {
          if (res.data.success) {
            _this.confirmAddress.id = res.data.re.id
            _this.confirmAddress.name = res.data.re.receiver
            _this.confirmAddress.tel = res.data.re.telephone
            _this.confirmAddress.province = res.data.re.province
            _this.confirmAddress.city = res.data.re.city
            _this.confirmAddress.county = res.data.re.district
            _this.confirmAddress.addressDetail = res.data.re.addrDetail
          } else {
            Toast.fail(res.data.msg)
          }
        }).catch(function () {
          Toast.fail('获取地址异常')
        })
      } else {
        _this.updateAddress(_this, this.$route.query.tempAddress)
      }
    },
    // 去地址页面
    toAddress: function () {
      sessionStorage.setItem('confirmNum', 1)
      this.$router.push({path: '/user/address'})
    },
    getCarGodsList () {
      let _this = this
      let goodsList = JSON.parse(sessionStorage.getItem('goodsList'))
      if (goodsList !== null) {
        orderApi.getOrderList(JSON.stringify(goodsList)).then(function (res) {
          if (res.data.re === null || res.data.re.length === 0) {
            Toast.fail('未获取到订单信息')
          }
          if (res.data.re !== null) {
            _this.list = res.data.re
          }
        })
      } else {
        _this.$router.go(-2)
      }
    },
    onSubmit: function () {
      let _this = this
      _this.isLoading = true
      Toast.loading({
        duration: 1500,
        mask: true,
        message: '正在玩命提交订单，请稍后.....'
      })
      let orderInfoList = []
      for (let i = 0; i < this.list.length; i++) {
        let temp = {
          goodsId: '',
          propertyId: '',
          num: '',
          salePrice: '',
          payPrice: '',
          discountPrice: ''
        }
        temp.goodsId = _this.list[i].goodsId
        temp.propertyId = _this.list[i].propertyId
        temp.num = _this.list[i].num
        temp.salePrice = _this.list[i].salePrice
        if (_this.list[i].isDiscount === 1) {
          temp.discountPrice = _this.list[i].discountPrice
        }
        if (this.list[i].isDiscount === 1) {
          temp.payPrice = this.list[i].discountPrice * this.memberDiscountPoint
        } else {
          temp.payPrice = this.list[i].salePrice * this.memberDiscountPoint
        }
        orderInfoList.push(temp)
      }
      let tempAddress = {
        addressId: _this.confirmAddress.id
      }
      orderInfoList.push(tempAddress)
      let tempTempAddress = {
        receiptName: _this.confirmAddress.name,
        receiptTel: _this.confirmAddress.tel,
        receiptAddress: _this.confirmAddress.province + _this.confirmAddress.city + _this.confirmAddress.county + _this.confirmAddress.addressDetail
      }
      // 封装订单总价
      let totalPrice = {
        totalPrice: _this.totalPrice,
        orderPrice: _this.orderPrice
      }
      orderInfoList.push(totalPrice)
      orderApi.confirmOrderInfo(JSON.stringify(orderInfoList)).then(function (res) {
        if (res.data.re !== null) {
          let temp = res.data.re[0]
          if (temp.goodsStatus === 1) {
            _this.isLoading = false
            // 置空sessionStorage
            sessionStorage.setItem('payGoodsList', sessionStorage.getItem('goodsList'))
            sessionStorage.setItem('payTotalPrice', sessionStorage.getItem('totalPrice'))
            sessionStorage.setItem('orderId', temp.orderId)
            sessionStorage.setItem('tempAddress', JSON.stringify(tempTempAddress))
            sessionStorage.removeItem('confirmNum')
            sessionStorage.removeItem('goodsList')
            sessionStorage.removeItem('totalPrice')
            Dialog.confirm({
              title: '提交订单信息',
              message: temp.showStatus,
              confirmButtonText: '去支付',
              cancelButtonText: '再次选择商品'
            }).then(() => {
              // 生成订单成功，跳转确认支付页面
              _this.$router.push('success')
            }).catch(() => {
              _this.$router.push({path: '/cart'})
            })
          }
          if (temp.goodsStatus === 0) {
            // 未成功跳转购物车重新选择商品
            _this.isLoading = false
            Dialog.alert({
              title: '提交订单失败信息',
              message: temp.showStatus,
              confirmButtonText: '返回购物车'
            }).then(() => {
              _this.$router.push({path: '/cart'})
            })
          }
        } else {
          Toast.fail('提交订单失败')
          _this.$router.push({path: '/cart'})
        }
      })
    }
  }
}
</script>
<style scoped>
  .address {
    padding-bottom: 2px;
  }
  .address::before{
    content: '';
    left: 0;
    right: 0;
    bottom: 0;
    height: 2px;
    position: absolute;
    background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
    background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
    background-size: 80px;
  }
  .order-ul {
    padding-bottom: 50px;
  }

  .order-ul li {
    border-bottom: 1px solid #eee;
  }

  .order-ul .van-card {
    background: #fff;
  }
</style>
